package cn.xiaoliu.hrm.service.impl;

import cn.xiaoliu.hrm.constant.EmployeeTypeConstant;
import cn.xiaoliu.hrm.domain.Employee;
import cn.xiaoliu.hrm.domain.LoginUser;
import cn.xiaoliu.hrm.domain.Tenant;
import cn.xiaoliu.hrm.dto.LoginUserDto;
import cn.xiaoliu.hrm.feign.ILoginUserFeignClient;
import cn.xiaoliu.hrm.mapper.EmployeeMapper;
import cn.xiaoliu.hrm.mapper.TenantMapper;
import cn.xiaoliu.hrm.query.TenantQuery;
import cn.xiaoliu.hrm.service.ITenantService;
import cn.xiaoliu.hrm.util.AjaxResult;
import cn.xiaoliu.hrm.util.ValidUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoliu
 * @since 2021-12-15
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private ILoginUserFeignClient loginUserFeignClient;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public Page<Tenant> loadTenantList(TenantQuery query, Page<Tenant> page) {
        //查询到分页数据和高级查询数据
        List<Tenant> tList = tenantMapper.loadTenantList(query,page);
        //page里面封装了的方法再把数据设置进去
        page.setRecords(tList);
        return page;
    }
    //店铺入驻
    @Override
    public AjaxResult entering(LoginUserDto dto) {
        //获取到employee
        //使用断言工具类校验参数
        //ValidUtils.assertNotNull(dto,"参数异常，请重新输入" );
        Employee employee = dto.getEmployee();
        //使用断言工具类校验参数
        //ValidUtils.assertNotNull(employee,"参数异常，请重新输入" );
        /**
         * 先保存auth中的t_login_user，然后返回主键用来保存t_user_meal
         * 再将t_login_user的主键返回用来保存t_emplyee然后返回主键用来保存t_tenant
         */
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(employee.getUsername());
        loginUser.setPassword(employee.getPassword());
        loginUser.setMealId(dto.getMealId());
        employee.setType(EmployeeTypeConstant.ADMIN_EMP);
        loginUser.setType(employee.getType());

        //保存t_employee
        AjaxResult ajaxResult = loginUserFeignClient.entering(loginUser);
        if (ajaxResult.isSuccess()){
            Integer loginId = (Integer) ajaxResult.getResultObj();
            employee.setLoginId(Long.valueOf(loginId));
            employee.setInputTime(new Date());
            employeeMapper.insert(employee);

            //保存t_tenant
            Tenant tenant = dto.getTenant();
            tenant.setAdminId(employee.getId());
            tenant.setRegisterTime(new Date());
            tenantMapper.insert(tenant);
        }
        return ajaxResult;
    }
}
